<html>
<script src="../../../../node_modules/trtc-js-sdk/trtc.js"></script>
<extend name="Public/base"/>
<block name="style">
    <style>
      #uploadVideoBtn {
        width: 120px;
        height: 30px;
        line-height: 30px;
        border: 1px solid #ccc;
        border-radius: 5px;
        text-align: center;
        background: #FFFFFF;
      }
    </style>
</block>
<block name="body">
    <script src="/Public/static/live/TRTCSDK/trtc.js"></script>
    <!--    <script src="/Public/static/live/TRTCSDK/share-client.js"></script>-->
    <!--    <script src="/Public/static/live/TRTCSDK/rtc-client.js"></script>-->
    <!--    <script src="/Public/static/live/TRTCSDK/rtc-detection.js"></script>-->
    <script src="/Public/static/live/TWEBLIVE/tweblive.js"></script>
    <div id="pusherView" style="width:500px; height:400px;"></div>
    <button onClick="startLive()" style="width: 100px; height: 30px; margin-top: 20px;">开播</button>
    <button onClick="startShare()" style="width: 100px; height: 30px; margin-top: 20px;">分享屏幕</button>
    <button onClick="stopShare()" style="width: 100px; height: 30px; margin-top: 20px;">停止分享屏幕</button>

    <script>
        var SDKAppId = {$SDKAppID};
        var userId = "{$userID}";
        var userSig = "{$userSig}";
        var roomId = "{$roomID}";
        let shareClient = null;
        let shareStream = null;

        function startLive() {
            // 1、创建 Pusher（推流）对象
            let pusher = TWebLive.createPusher({userID: userId});
            // console.log(pusher);return false;
            // 2、设置渲染界面，且从麦克风采集音频，从摄像头采集视频（默认720p）
            pusher.setRenderView({
                elementID: 'pusherView',
                audio: true,
                video: true
            }).then(() => {
                // 3、填入 sdkappid roomid 等信息，推流
                // url 必须以 `room://` 开头
                let url = `room://sdkappid=` + SDKAppId + `&roomid=` + roomId + `&userid=` + userId + `&usersig=` + userSig + `&livedomainname={$liveDomainName}&streamid={$streamid}`;
                console.log(url)
                pusher.startPush(url).then(() => {
                    console.log('pusher | startPush | ok');
                });
            }).catch(error => {
                console.error('pusher | setRenderView | failed', error);
            });
        }

        function startShare() {
            if (!TRTC.isScreenShareSupported()) {
                layer.msg('当前浏览器不支持屏幕分享');
                return;
            }

            //step1：创建屏幕分享客户端
            shareClient = TRTC.createClient({
                mode: 'rtc',
                sdkAppId: SDKAppId,
                userId: userId,
                userSig: userSig
            });

            //step2：创建屏幕分享流
            // 仅采集屏幕分享视频流
            // shareStream = TRTC.createStream({ audio: false, screen: true, userId });
            // 采集麦克风及屏幕分享视频流
            shareStream = TRTC.createStream({audio: true, screen: true});
            // 采集系统音频及屏幕分享视频流
            // const shareStream = TRTC.createStream({ screenAudio: true, screen: true });
            try {
                async function start() {
                    //step3：初始化屏幕分享流
                    await shareStream.initialize();

                    //step4：屏幕分享客户端进房
                    await shareClient.join({roomId});

                    //step5：屏幕分享客户端发布屏幕分享流
                    await shareClient.publish(shareStream);

                    // 当用户通过浏览器自带的按钮停止屏幕分享时，会监听到 screen-sharing-stopped 事件
                    shareStream.on('screen-sharing-stopped', event => {
                        console.log('share stream video track ended');
                        shareClient.leave();
                    });
                }

                start();
            } catch (e) {
                // 当屏幕分享流初始化失败时, 提醒用户并停止后续进房发布流程
                switch (e.name) {
                    case 'NotReadableError':
                        // 提醒用户确保系统允许当前浏览器获取屏幕内容
                        return;
                    case 'NotAllowedError':
                        if (e.message === 'Permission denied by system') {
                            // 提醒用户确保系统允许当前浏览器获取屏幕内容
                        } else {
                            // 用户拒绝/取消屏幕分享
                        }
                        return;
                    default:
                        // 初始化屏幕分享流时遇到了未知错误，提醒用户重试
                        return;
                }
            }
            // audio 与 screenAudio 属性不能同时设为true, 关于screenAudio更多信息会在本文第五部分介绍。
            shareStream.setScreenProfile('1080p_2');
        }

        function stopShare() {
            async function stop() {
                // 屏幕分享客户端停止推流
                await shareClient.unpublish(shareStream).then(() => {
                    // 取消发布本地流成功

                    // 关闭屏幕分享流
                    shareStream.close();
                });

                console.log('share stream video track ended');
                shareClient.leave();
            }

            stop();
        }

    </script>
</block>

<block name="script">
    <script src="__STATIC__/thinkbox/jquery.thinkbox.js"></script>
    <script type="text/javascript">
        //导航高亮
        highlight_subnav('{:U("Manage/live")}');
    </script>
</block>

</html>
